package com.ilibrary.web.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.ilibrary.base.MyAjaxAction;
import com.ilibrary.base.MyBaseVO;
import com.ilibrary.constants.MyConstants;
import com.ilibrary.constants.MyMsgConstants;
import com.ilibrary.service.BookService;
import com.ilibrary.service.BorrowService;
import com.ilibrary.utils.MyColumnIndicator;
import com.ilibrary.utils.MyTools;
import com.ilibrary.web.dto.ResultDto;
import com.ilibrary.web.vo.AdminVO;
import com.ilibrary.web.vo.BorrowVO;

public class DoRenewBorrowAction extends MyAjaxAction {
	
	private BorrowService borrowService;
	
	public BorrowService getBorrowService() {
		return borrowService;
	}
	public void setBorrowService(BorrowService borrowService) {
		this.borrowService = borrowService;
	}
	
	@Override
	protected JSONObject doExecute(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		String bookId = request.getParameter("bookId");
		JSONObject jo = new JSONObject();
		
		AdminVO adminVO = (AdminVO) session.getAttribute(MyConstants.ILIBRARY_LOGIN_ADMIN);
		
		ResultDto<BorrowVO> resultDto = borrowService.findByBookId(bookId);
		if(!resultDto.isSuccess()) {
			jo.put("success", false);
			jo.put("msg", resultDto.getMsg());
			return jo;
		}
		
		BorrowVO borrowVO = resultDto.getFirstResult();
		if(borrowVO.getBorrowRenewNum() >= MyConstants.BORROW_RENEW_NUM_MAX) {
			jo.put("success", false);
			jo.put("msg", MyMsgConstants.BORROW_RENEW_CNT_REACH_MAX);
			return jo;
		}else {
			borrowVO.setBorrowRenewNum(borrowVO.getBorrowRenewNum()+1);
			borrowVO.setBorrowDeadline(MyTools.getNextXDayDate(borrowVO.getBorrowDeadline(), MyConstants.BOOK_LOAN_DAY_MAX));
			borrowVO.setUpdateDt(new Date());
			borrowVO.setUpdateUser(adminVO.getAdminId());
			ResultDto<MyBaseVO> resultDto2 = borrowService.update(borrowVO);
		}
		jo.put("success", true);
		return jo;
	}

}
